package com.iqiyi.dbagent.base.utils.data;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.iqiyi.dbagent.base.config.MySqlConfig;

/**
 * 
* @Title: DataSourceUtil.java
* @Package com.iqiyi.dbagent.base.utils
* @Description: 入库数据源工具类
* @author 王年明
* @date 2015年11月25日 下午9:50:55
* @version V1.0
 */
public class DataSourceUtil {
	
	/** 使用配置文件dbconfig.properties构建Druid数据源. */
	public static final int DRUID_MYSQL_SOURCE = 0;
	
	/** The duird mysql source. */
	private static DataSource duirdMysqlSource;
	
	/** 使用配置文件dbconfig.properties构建Dbcp数据源. */
	public static final int DBCP_MYSQL_SOURCE = 1;
	
	/** The dbcp source. */
	private static DataSource dbcpSource;
	
	/**
	 * 根据类型获取数据源.
	 *
	 * @param sourceType 数据源类型
	 * @return druid或者dbcp数据源
	 * @throws Exception the exception
	 * @NotThreadSafe
	 */
	@SuppressWarnings("static-access")
    public static final DataSource getDataSource(int sourceType,MySqlConfig myConfig)
		throws Exception {
		DataSource dataSource = null;
		switch(sourceType) {
		case DRUID_MYSQL_SOURCE:			
			if (duirdMysqlSource == null) {
				duirdMysqlSource = DruidDataSourceFactory.createDataSource(myConfig.getInstance().getP());
			}
			dataSource = duirdMysqlSource;
			break;
		case DBCP_MYSQL_SOURCE:
			if (dbcpSource == null) {
				dbcpSource = BasicDataSourceFactory.createDataSource(myConfig.getInstance().getP());
			}
			dataSource = dbcpSource;
			break;
		}
		return dataSource;
	}
	
	/**
	 * 获取同步连接
	 * @param sourceType
	 * @param myConfig
	 * @return
	 * @throws Exception 
	 * @throws SQLException
	 */
	public static Connection getSyncConn(int sourceType,MySqlConfig myConfig) throws SQLException, Exception{
	    Connection conn = getDataSource(sourceType, myConfig).getConnection();
	    conn.setAutoCommit(false);
	    return conn;
	}

	/**
	 * 
	 * @param sourceType
	 * @param myConfig
	 * @return
	 * @throws SQLException
	 * @throws Exception
	 */
	public static Connection getNSyncConn(int sourceType,MySqlConfig myConfig) throws SQLException, Exception{
	    Connection conn = getDataSource(sourceType, myConfig).getConnection();
        conn.setAutoCommit(true);
        return conn;
	}

    public static DataSource getDuirdMysqlSource() {
        return duirdMysqlSource;
    }

    public static void setDuirdMysqlSource(DataSource duirdMysqlSource) {
        DataSourceUtil.duirdMysqlSource = duirdMysqlSource;
    }

    public static DataSource getDbcpSource() {
        return dbcpSource;
    }

    public static void setDbcpSource(DataSource dbcpSource) {
        DataSourceUtil.dbcpSource = dbcpSource;
    }
	
}
